package zzzxb.generation;

import org.junit.Test;
import org.omg.CosNaming.NamingContextPackage.NotFound;

import java.io.*;

/**
 * @author Zzzxb  2019/8/10 8:18
 * @description: read-write operation
 */
public class RWOperation {

    @Test
    public void readFileTest() {
        try {
            System.out.println(readFile("d:\\a.txt"));
    } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void writeFileTest() {
        try {
            writeFile("d:\\b.txt", "Hello\r\n龙行龘龘犄角旮旯");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文件  Encoding = "UTF-8"
     *
     * @param path 被读取文件路径
     * @return content 被读取文件内容
     * @throws IOException
     */
    public String readFile(String path) throws IOException{
        InputStreamReader inputStreamReader = null;
        String content = null;
        inputStreamReader =
                new InputStreamReader(new FileInputStream(new File(path)),
                        "UTF-8");
        int len = -1;
        // 根据文件大小生成 char 数组
        char[] chars = new char[(int) (new File(path).length())];
        while ((len = inputStreamReader.read(chars)) != -1) {
            content = new String(chars, 0, len);
        }
        inputStreamReader.close();
        return content;
    }

    /**
     * 写入文件 Encoding = "UTF-8"
     *
     * @param path    写入文件路径
     * @param content 写入文件内容
     * @throws Exception
     */
    public void writeFile(String path, String content) throws Exception {
        OutputStreamWriter outputStreamWriter = null;
        try {
            outputStreamWriter =
                    new OutputStreamWriter(new FileOutputStream(new File(path)),
                            "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            System.err.println("写入文件未找到");
            e.printStackTrace();
        }
        outputStreamWriter.write(content);
        outputStreamWriter.flush();
        outputStreamWriter.close();
        System.out.println("success");
    }
}
